/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uc.edu.server;

import java.util.SortedSet;
import java.util.TreeSet;

/**
 *
 * @author tony
 */
public class MessageStore implements IMessageStore
{

    private SortedSet<MessageWithID> backingStore;
    private long maxID;

    /**
     * Constructor. Initialize backingStore.
     */
    public MessageStore()
    {
        backingStore = new TreeSet<>();
        maxID = 0L;
    }

    /**
     * Add a message to the backing store and
     * assign it an id.
     * @param msg
     * @return long -- generated id number
     */
    @Override
    public long addMessage(MessageWithID msg)
    {
        // Whether this message already has an id or
        // not, set its id to the next available
        // slot in the list -- ie, the current max + 1.
        setMaxID(getMaxID() + 1);
        msg.setID(maxID);
        backingStore.add(msg);
        return getMaxID();
    }

    @Override
    public long getMaxID()
    {
        return maxID;
    }

    @Override
    public void setMaxID(long newMax)
    {
        maxID = newMax;
    }

    /**
     * Return the first message with message id > lastID
     *
     * This is a terribly inefficient way to go about this.
     * A linked list as the backing store might be better,
     * along with a "pointer" to the last accessed message.
     * 
     * @param lastID
     * @return MessageWithID
     */
    @Override
    public MessageWithID nextMessage(long lastID)
    {
        // Iterate through the collection. Break out of the loop
        // when we get to one that's > lastID.
        // If collection is empty, or no message > lastID,
        // return null.
        MessageWithID retMsg = null;
        for (MessageWithID msg : backingStore)
          {
            if (msg.getID() > lastID)
              {
                retMsg = msg;
                break;
              }
          } // end for
        return retMsg;
    } // end nextMessage()
} // end class MessageStore
